package com.newworld.dmsapp2.activity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.adapter.HouseManagePeopleAdapter;
import com.newworld.dmsapp2.fragment.bean.HouseManagePeople;
import com.newworld.dmsapp2.fragment.bean.RelationType;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

@SuppressWarnings({ "deprecation" })
public class HouseManagePeopleListActivity extends BaseActivity {

	private SwipeMenuListView lv;
	private ArrayList<HouseManagePeople> list = new ArrayList<HouseManagePeople>();
	private HouseManagePeopleAdapter adapter;
	private User user;
	private Intent intent;
	private ProgressBar progressBar;
	private LinearLayout leftlayout;
	private LinearLayout rightlayout;
	public static String str;
	private SwipeMenuCreator creator;
	private String houseId;
	private List<RelationType> relationTypeList = new ArrayList<RelationType>();
	private String houseUserId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_house_manage_people_list);

		initViews();
		initEvents();

	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		TextView titleView = (TextView) findViewById(R.id.titlebar_both_center_title);
		TextView righttx = (TextView) findViewById(R.id.titlebar_both_right_text);
		titleView.setText(Config.TITLE_HOUSE_MANAGEMENT);
		righttx.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.make_invetecode));
		righttx.setText("");
		leftlayout = (LinearLayout) findViewById(R.id.titlebar_both_left_layout);
		progressBar = (ProgressBar) findViewById(R.id.proBar_get_data);

		rightlayout = (LinearLayout) findViewById(R.id.titlebar_both_right_layout);
		intent = getIntent();
		if (intent != null) {
			houseId = intent.getExtras().getString("houseId");
			houseUserId = intent.getExtras().getString("houseUserId");
		}
		if (houseUserId != null) {
			rightlayout.setVisibility(View.INVISIBLE);
		}
		lv = (SwipeMenuListView) findViewById(R.id.housemanagepeople_lv);
		init();
		for (HouseManagePeople p : list) {
			Log.e("relatePeople", p.toString());
		}

		creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				switch (menu.getViewType()) {
				case 0:
					createMenu1(menu);
					break;
				case 1:
					// createMenu2(menu);
					break;
				default:
					break;
				}

			}

			private void createMenu1(SwipeMenu menu) {
				SwipeMenuItem item1 = new SwipeMenuItem(getApplicationContext());
				item1.setBackground(new ColorDrawable(Color.rgb(0xE5, 0x18,
						0x5E)));
				item1.setWidth(dp2px(90));
				item1.setIcon(getResources().getDrawable(R.drawable.str_agree));
				menu.addMenuItem(item1);
				SwipeMenuItem item2 = new SwipeMenuItem(getApplicationContext());

				item2.setBackground(new ColorDrawable(Color.rgb(0x30, 0xB1,
						0xF5)));
				item2.setWidth(dp2px(90));
				item2.setIcon(getResources().getDrawable(
						R.drawable.str_notagree));
				menu.addMenuItem(item2);
			}

		};
		// set creator
		lv.setMenuCreator(creator);

		// step 2. listener item click event

	}

	private void init() {
		// TODO Auto-generated method stub
		user = SingleSample.getInstance(this).getUser();
		user.getUsertype();

		if (houseUserId != null) {
			intoMessageRelateHouse();

		} else {
			intoRelateHouseList();
		}

	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub
		// 点击titlebar左边按钮响应事件
		leftlayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*if (intent.getExtras().getString("activity") != null
						&& intent.getExtras().getString("activity")
								.equals("MainMessageFragment")) {
					finish();
				} else {
					intent = new Intent(HouseManagePeopleListActivity.this,
							HouseManageListActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(intent);
					finish();
				}*/
				intentActivity(HouseManagePeopleListActivity.this,
						HouseManageListActivity.class);

			}
		});
		// 点击titlebar右边按钮
		rightlayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getRelationType();

			}

		});
		// 列表item左滑显示的菜单的点击事件
		lv.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(final int position, SwipeMenu menu,
					int index) {
				// 未处理状态
				if (!list.get(position).getStatusType_typeCode()
						.equals(Config.HOUSE_MANAGEMENT_ATATCHED)) {
					switch (index) {
					case 0:
						// open

						final CustomDialog dialog = new CustomDialog(
								HouseManagePeopleListActivity.this);
						dialog.setTitle("房屋关联");
						dialog.setDetial("确定同意该用户房屋关联请求？");
						dialog.setLeftOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
							}
						});
						dialog.setRightOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								agreeHouseRelate(list.get(position)
										.getHouseUserId());

							}

						});
						dialog.show();

						break;
					case 1:
						// delete
						// delete(item);
						final CustomDialog dialog1 = new CustomDialog(
								HouseManagePeopleListActivity.this);
						dialog1.setTitle("房屋关联");
						dialog1.setDetial("确定不同意该用户房屋关联请求？");
						dialog1.setLeftOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog1.dismiss();
							}
						});
						dialog1.setRightOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog1.dismiss();
								disagreeHouseRelate(list.get(position)
										.getHouseUserId());

							}

						});
						dialog1.show();
						break;
					}
				} else if (list.get(position).getStatusType_typeCode()
						.equals(Config.HOUSE_MANAGEMENT_ATATCHED)) {
					switch (index) {
					case 0:
						// open

						final CustomDialog dialog = new CustomDialog(
								HouseManagePeopleListActivity.this);
						dialog.setTitle("房屋关联");
						dialog.setDetial("确定删除该用户？");
						dialog.setLeftOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
							}
						});
						dialog.setRightOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								list.remove(position);
								adapter.notifyDataSetChanged();
								dialog.dismiss();

							}
						});
						dialog.show();

						break;
					}
				}

			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			intentActivity(HouseManagePeopleListActivity.this,
					HouseManageListActivity.class);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	// 获取业主关系类型
	private void getRelationType() {
		// TODO Auto-generated method stub

		new AsyncTask<Void, Void, Void>() {

			private String message;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManagePeopleListActivity.this,
							"请检查网络连接！", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					try {

						String url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_GETRELATIONTYPELIST)
										.get(0).getFunctionUrl();
						Map<String, String> map = new HashMap<String, String>();
						map.put("functionCode",
								Config.FUNCTION_REAL_GETRELATIONTYPELIST);
						String setsessionid = "";
						user = SingleSample.getInstance(HouseManagePeopleListActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,setsessionid);
						Log.e("获取业主关系类型result", result);
						if (new JSONObject(result).getString("flag").equals(
								"success")) {
							String rows = new JSONObject(result)
									.getString("rows");
							Type type = new TypeToken<List<RelationType>>() {
							}.getType();
							Gson gson = new Gson();
							relationTypeList = gson.fromJson(rows, type);

						}
						message = new JSONObject(result).getString("message");

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				final List<RelationType> relationTypeNotOwnerList = new ArrayList<RelationType>();
				List<String> relationStringList = new ArrayList<String>();
				Toast.makeText(HouseManagePeopleListActivity.this, message,
						Toast.LENGTH_SHORT).show();
				progressBar.setVisibility(View.INVISIBLE);
				
				for (RelationType relationType : relationTypeList) {
					if (!relationType.getTypeCode().equals("owner")) {
						relationTypeNotOwnerList.add(relationType);
						relationStringList.add(relationType.getTypeName());
					}
				}
				new AlertDialog.Builder(HouseManagePeopleListActivity.this)
						.setTitle("选择关系")
						.setAdapter(
								new ArrayAdapter<String>(
										HouseManagePeopleListActivity.this,
										R.layout.list_ok, relationStringList),
								new android.content.DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method
										// stub

										Intent intent = new Intent(
												HouseManagePeopleListActivity.this,
												HouseManageMakeInvetecodeActivity.class);
										intent.putExtra("houseId", houseId);
										intent.putExtra(
												"relationTypeId",
												relationTypeNotOwnerList.get(
														which).getId());
										startActivity(intent);
										finish();
									}
								}

						)

						.create().show();
			}
		}.execute(null, null, null);
	}

	// 户主进一步查询已关联和正在关联中的房屋
	private void intoRelateHouseList() {
		// TODO Auto-generated method stub
		// 请求列表信息
		new AsyncTask<Void, Void, Void>() {

			private String getListMessge;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManagePeopleListActivity.this,
							"请检查网络连接！", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					try {
						String url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_HOUSERELATEDETAIL)
										.get(0).getFunctionUrl();

						Map<String, String> map = new HashMap<String, String>();
						map.put("functionCode",
								Config.FUNCTION_REAL_HOUSERELATEDETAIL);
						map.put("houseId", houseId);
						String setsessionid = "";
						user = SingleSample.getInstance(HouseManagePeopleListActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,setsessionid);
						Log.e("获取关联用户的列表", result);
						if (new JSONObject(result).getString("flag").equals(
								"success")) {

							String rows = new JSONObject(result)

							.getString("rows");
							if (!rows.equals("")) {
								Type type = new TypeToken<List<HouseManagePeople>>() {
								}.getType();
								Gson gson = new Gson();
								list = gson.fromJson(rows, type);
							} else {
								list = new ArrayList<HouseManagePeople>();
							}
						}

						getListMessge = new JSONObject(result)

						.getString("message");
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				progressBar.setVisibility(View.INVISIBLE);
				Toast.makeText(HouseManagePeopleListActivity.this,
						getListMessge, Toast.LENGTH_SHORT).show();
				if (list != null) {
					adapter = new HouseManagePeopleAdapter(
							HouseManagePeopleListActivity.this, list);
					lv.setAdapter(adapter);
				} else {
					list = new ArrayList<HouseManagePeople>();
					adapter = new HouseManagePeopleAdapter(
							HouseManagePeopleListActivity.this, list);
					lv.setAdapter(adapter);
				}
			}
		}.execute(null, null, null);

	}

	// 消息处理时，户主进一步查询自己的某个房屋的单个关联申请
	private void intoMessageRelateHouse() {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String getListMessge;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManagePeopleListActivity.this,
							"请检查网络连接！", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					try {
						String url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_INTORELATEHOUSE)
										.get(0).getFunctionUrl();

						Map<String, String> map = new HashMap<String, String>();
						map.put("functionCode",
								Config.FUNCTION_REAL_HOUSERELATEDETAIL);
						map.put("houseUserId", houseUserId);
						String setsessionid = "";
						user = SingleSample.getInstance(HouseManagePeopleListActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,setsessionid);
						Log.e("获取关联用户的列表", result);
						if (new JSONObject(result).getString("flag").equals(
								"success")) {

							String rows = new JSONObject(result)

							.getString("rows");
							if (!rows.equals("")) {
								Type type = new TypeToken<List<HouseManagePeople>>() {
								}.getType();
								Gson gson = new Gson();
								list = gson.fromJson(rows, type);
							} else {
								list = new ArrayList<HouseManagePeople>();
							}
						}

						getListMessge = new JSONObject(result)

						.getString("message");
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				progressBar.setVisibility(View.INVISIBLE);
				Toast.makeText(HouseManagePeopleListActivity.this,
						getListMessge, Toast.LENGTH_SHORT).show();
				if (list != null) {
					adapter = new HouseManagePeopleAdapter(
							HouseManagePeopleListActivity.this, list);
					lv.setAdapter(adapter);
				} else {
					list = new ArrayList<HouseManagePeople>();
					adapter = new HouseManagePeopleAdapter(
							HouseManagePeopleListActivity.this, list);
					lv.setAdapter(adapter);
				}
			}
		}.execute(null, null, null);

	}

	private void agreeHouseRelate(final String houseUserId) {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String agressMessage;
			@SuppressWarnings("unused")
			private String agressFlag;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManagePeopleListActivity.this,
							"请检查网络连接！", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					try {

						String url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_ANSWERHOUSERELATE)
										.get(0).getFunctionUrl();
						// 户主处理未关联
						Map<String, String> map = new HashMap<String, String>();
						map.put("functionCode",
								Config.FUNCTION_REAL_ANSWERHOUSERELATE);
						map.put("houseUserId", houseUserId);
						map.put("agree", "yes");
						String setsessionid = "";
						user = SingleSample.getInstance(HouseManagePeopleListActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,setsessionid);
						Log.e("户主同意result", result);
						agressMessage = new JSONObject(result)
								.getString("message");
						agressFlag = new JSONObject(result).getString("flag");

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				Toast.makeText(HouseManagePeopleListActivity.this,
						agressMessage, Toast.LENGTH_SHORT).show();

				intoRelateHouseList();

			}
		}.execute(null, null, null);
	}

	// 户主不同意关联
	private void disagreeHouseRelate(final String houseUserId) {
		// TODO Auto-generated method stub

		new AsyncTask<Void, Void, Void>() {

			private String notAgressMessage;
			@SuppressWarnings("unused")
			private String disagressFlag;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManagePeopleListActivity.this,
							"请检查网络连接！", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManagePeopleListActivity.this)) {
					try {
						String url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_ANSWERHOUSERELATE)
										.get(0).getFunctionUrl();
						// 户主处理未关联
						Map<String, String> map = new HashMap<String, String>();
						map.put("functionCode",
								Config.FUNCTION_REAL_ANSWERHOUSERELATE);
						map.put("houseUserId", houseUserId);
						map.put("agree", "no");
						String setsessionid = "";
						user = SingleSample.getInstance(HouseManagePeopleListActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,setsessionid);
						Log.e("户主不同意result", result);
						notAgressMessage = new JSONObject(result)
								.getString("message");
						disagressFlag = new JSONObject(result)
								.getString("flag");
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				Toast.makeText(HouseManagePeopleListActivity.this,
						notAgressMessage, Toast.LENGTH_SHORT).show();
				intoRelateHouseList();

			}
		}.execute(null, null, null);
	}
}